package com.topisv.tms.web.stock.instorage;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.topisv.tms.entity.AreaGroup;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.EdiGoodsSku;
import com.topisv.tms.entity.stock.instorage.InstorageCountItem;
import com.topisv.tms.entity.stock.instorage.InstorageCountTask;
import com.topisv.tms.entity.stock.instorage.pre.InstorageBillItemPre;
import com.topisv.tms.exception.PaiUException;
import com.topisv.tms.service.AreaGroupService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.EdiGoodsSkuService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.stock.instorage.InstorageCountTaskService;
import com.topisv.tms.service.stock.preinstorage.PreInstorageService;
import com.topisv.tms.service.work.WorkTaskService;
import com.topisv.tms.utils.EdiOrderUtil;

/**
 * 入库点收_control
 * @author ch
 */
@Controller
@RequestMapping(value = "/v2_instorageCount")
public class InstorageCountController {

	private static final Logger logger = LoggerFactory.getLogger(InstorageCountController.class);

	@Autowired
	private CustomersService customersService;
	@Autowired
	private InstorageCountTaskService instorageCountTaskService;
	@Autowired
	private AreaGroupService areaGroupService;
	@Autowired
	private EdiGoodsSkuService ediGoodsSkuService ;
   @Autowired
    private WorkTaskService workTaskService;
	
	/**
	 * 导向点收任务列表页面
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "toCountTaskListPage")
	public String toCountTaskListPage(ServletRequest request,HttpServletResponse response,Model model){
		try {
			
			//当前用户关联的商家列表
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			List<Customers> customerList=this.customersService.loadCustomerByAuthority(curUser);
			model.addAttribute("customerList",customerList);
			model.addAttribute("countcustomerCodeList",customerList);
			model.addAttribute("userType",curUser.userType);
		    
		    //我的任务
		    Map<String, Object> param_my=new HashMap<String, Object>();
		    param_my.put("workerUuid", curUser.jobuuid);
		    param_my.put("status", "myTask"); //任务状态 （undo.创建点收任务 doing:点收中 finish.点收完成）
		    List<InstorageCountTask> myTaskList=this.instorageCountTaskService.loadTaskByParam(param_my);
		    model.addAttribute("myTaskList",myTaskList);
		    
		    //如果是派友用户,初始化数据
			if("paiu".equals(curUser.userType)){
				//未分配的拣货任务
			    Map<String, Object> param=new HashMap<String, Object>();
			    param.put("customerCodes", StringUtils.isBlank(curUser.customers)?"blank":curUser.customers);
			    param.put("areagroups", StringUtils.isBlank(curUser.areagroups)?"blank":curUser.areagroups);
			    param.put("status", "undo"); //任务状态 （undo.创建点收任务 doing:点收中 finish.点收完成）
			    List<InstorageCountTask> untakedTaskList=this.instorageCountTaskService.loadTaskByParam(param);
			    model.addAttribute("untakedTaskList",untakedTaskList);
			    
			}
		    
		    //如果是商家用户,初始化数据
			if("customer".equals(curUser.userType)){
				//未分配的拣货任务
				String customerCode=curUser.customerCode;
			    Map<String, Object> param=new HashMap<String, Object>();
			    param.put("customerCodes", StringUtils.isBlank(customerCode)?"blank":customerCode);
			    param.put("areagroups", StringUtils.isBlank(curUser.areagroups)?"blank":curUser.areagroups);
			    param.put("status", "undo"); //任务状态 （undo.创建点收任务 doing:点收中 finish.点收完成）
			    List<InstorageCountTask> untakedTaskList=this.instorageCountTaskService.loadTaskByParam(param);
			    model.addAttribute("untakedTaskList",untakedTaskList);
			    
			    //初始化仓库数据
				if(StringUtils.isNotBlank(customerCode)){
					List<AreaGroup> warehouseList=this.areaGroupService.loadAreaGroupByAuthority(curUser,customerCode);
					model.addAttribute("warehouseList", warehouseList);
					model.addAttribute("countwarehouseList", warehouseList);

				}
			}
		
		} catch (Exception e) {
			logger.error("error",e);
		}
	    
		return "instorage/instorageCountTaskList";
	}
	
	
	/**
	 * 查询拣货任务列表
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "queryTaskList",method = RequestMethod.POST)
	public void queryTaskList(ServletRequest request,HttpServletResponse response) throws Exception {
		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			//查出当前用户关联的商家列表
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		    //查询未分配的拣货任务
			String warehouseCode=request.getParameter("warehouseCode");
			String customerCode=request.getParameter("customerCode");
			Map<String, Object> param=new HashMap<String, Object>();
			if(StringUtils.isBlank(customerCode)){
				param.put("customerCodes", this.customersService.loadCustomerByAuthority(curUser.jobuuid));
			}else{
				param.put("customerCodes", customerCode);
			}
			
			if(StringUtils.isBlank(warehouseCode)){
				param.put("areagroups", curUser.areagroups);
			}else{
				param.put("areagroups", warehouseCode);
			}
			
			param.put("status", "undo"); //任务状态 （undo.创建点收任务 doing:点收中 finish.点收完成）
			List<InstorageCountTask> untakedTaskList=this.instorageCountTaskService.loadTaskByParam(param);
			json.put("status","success");
			json.put("untakedTaskList",untakedTaskList);
		
		} catch (Exception e) {
			logger.error("error",e);
			json.put("status","error");
			json.put("content",e.getMessage());
		}
		out.print(json.toString());
	}
	@RequestMapping(value = "queryMyTaskList",method = RequestMethod.POST)
	public void queryMyTaskList(ServletRequest request, HttpServletResponse response) throws Exception {
		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			//查出当前用户关联的商家列表
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			//我的任务 
			Map<String, Object> param_my=new HashMap<String, Object>();
			String countwarehouseCode=request.getParameter("countwarehouseCode");
			String countcustomerCode=request.getParameter("countcustomerCode");
			String countstatus=request.getParameter("countstatus");
			String countbillCode=request.getParameter("countbillCode");
			if(StringUtils.isBlank(countcustomerCode)){
				param_my.put("customerCodes", this.customersService.loadCustomerByAuthority(curUser.jobuuid));
			}else{
				param_my.put("customerCodes", countcustomerCode);
			}
			
			if(StringUtils.isBlank(countwarehouseCode)){
				param_my.put("areagroups", curUser.areagroups);
			}else{
				param_my.put("areagroups", countwarehouseCode);
			}
			if(StringUtils.isBlank(countstatus)){
				param_my.put("countstatus", "");
				
			}else{
				param_my.put("countstatus", countstatus);
			}
			if(StringUtils.isBlank(countbillCode)){
				param_my.put("countbillCode", "");
			}else{
				param_my.put("countbillCode", countbillCode);
			}
			param_my.put("workerUuid", curUser.jobuuid);
			param_my.put("status", "myTask"); //任务状态 （undo.创建点收任务 doing:点收中 finish.点收完成）
		    List<InstorageCountTask> myTaskList=this.instorageCountTaskService.loadTaskByParam(param_my);
		    json.put("status","success");
			json.put("myTaskList",myTaskList);
		
		} catch (Exception e) {
			logger.error("error",e);
			json.put("status","error");
			json.put("content",e.getMessage());
		}
		out.print(json.toString());
	}
	/**
	 * 领取点收任务
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ajaxTakeTask")
	@ResponseBody
	public String ajaxTakeTask(ServletRequest request,HttpServletResponse response) {
		try {	
			Long taskId=Long.valueOf(request.getParameter("taskId")+""); 
			ShiroUser curUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
			
			//领取任务
			String result = this.instorageCountTaskService.takeTask(taskId,curUser.jobuuid);
			if ("token".equals(result)) {
                return "任务已被领取!请核查";
            }else if ("success".equals(result)) {
                return "true";
            }else {
                return "网络繁忙，请稍后重试...";
            }
		} catch (Exception e) {
			logger.error("error",e);
			return "网络繁忙，请稍后重试...";
		}
	}
	
	/**
	 * 导向点收页面
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "toInstorageCountPage/{taskId}", method = RequestMethod.GET)
	public String toInstorageCountPage(@PathVariable("taskId") Long taskId, Model model) {
		try {
		      InstorageCountTask  task=this.instorageCountTaskService.loadById(taskId);
		      model.addAttribute("task", task);
		      
		      List<InstorageCountItem> itemList_single=this.instorageCountTaskService.loadByTaskCode(task.getTaskCode(),"single");
		      model.addAttribute("itemList_single", itemList_single);
		      
		      List<InstorageCountItem> itemList_box=this.instorageCountTaskService.loadByTaskCode(task.getTaskCode(),"box");
		      model.addAttribute("itemList_box", itemList_box);
			
		} catch (Exception e) {
			logger.error("error",e);
		}
		return "instorage/instorageCount";
	}
	
	/**
	 * 导向点收页面(新流程)
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "toInstorageCountPageNew/{taskId}", method = RequestMethod.GET)
	public String toInstorageCountPageNew(@PathVariable("taskId") Long taskId, Model model) {
		try {
		      InstorageCountTask  task=this.instorageCountTaskService.loadById(taskId);
		      model.addAttribute("task", task);
		      List<InstorageCountItem> items=this.instorageCountTaskService.findByBillCode(task.getBillCode());
		      for(InstorageCountItem item:items){
					item.setEdiGoodsSku(ediGoodsSkuService.findByCustomerCodeAndSku(item.getCustomerCode(),item.getSku()));
			  }
		      List<InstorageBillItemPre> preItems= this.instorageCountTaskService.loadBillItemPres(task.getBillCode());
		  	
	    		if(null != preItems ){
					Map<String,Integer> countMap = new HashMap<String,Integer>();
					
					for(InstorageBillItemPre itemPre : preItems){
						countMap.put((itemPre.getSkuCode() + "_" + 
						    (itemPre.getBatchCode() == null ? "" : itemPre.getBatchCode()) + "_" + 
						    (itemPre.getProductDate() == null ? "" : itemPre.getProductDate()) + "_" +
						    (itemPre.getExpireDate() == null ? "" : itemPre.getExpireDate())), itemPre.getGoodsNum());
					}
					for(InstorageCountItem cItem : items){
						cItem.setPlanNum((countMap.get(cItem.getSku() + "_" + (cItem.getBatchCode() == null ? "" : cItem.getBatchCode()) + "_" +
						    (cItem.getProductDate() == null ? "" : cItem.getProductDate()) + "_" + 
						    (cItem.getExpireDate() == null ? "" : cItem.getExpireDate()))));
					}
				}
	    		
		      model.addAttribute("items", items);
			
		} catch (Exception e) {
			logger.error("error",e);
		}
		return "instorage/instorageCountNew";
	}
	
	@Autowired
	private PreInstorageService preInstorageService;
	
	/**
	 * 点收新流程
	 * @param request
	 * @param response
	 */
	@SuppressWarnings("unchecked")
    @RequestMapping(value = "ajaxCountNew")
	public void ajaxCountNew(ServletRequest request,HttpServletResponse response) {

		JSONObject json = null;
		PrintWriter out = null;
		Map<String, Object> resultMap = new HashMap<String, Object>();
		boolean isLockSuccess = false;
		String taskCode=request.getParameter("taskCode");
		try {
			json = new JSONObject();
			out = response.getWriter();
			
			isLockSuccess = workTaskService.lock("PC.ajaxCountNew", taskCode, "-");
            if (!isLockSuccess) {
                json.put("status", "error");
                json.put("content", "当前任务已在处理中，请勿重复处理！");
                return;
            }
            
			//获取参数
			String billCode=request.getParameter("billCode");
			String sku=request.getParameter("sku");
			String customerCode=request.getParameter("customerCode");
			Integer num=Integer.valueOf(request.getParameter("num"));
			String errorFlag = request.getParameter("errorflag");
			
			//EditBy yinglei_lian 2016.10.26 Bug0000588 
			String content = instorageCountTaskService.findSkuExist(billCode, sku, customerCode);
			if(content != null){
				json.put("status","skuNotExist");
				json.put("content",content);
				logger.error("---------sku :"+sku+" not exist!-----");
			}else {
				//EditBy yinglei_lian 2016.10.26 Bug0000588 
				resultMap =this.instorageCountTaskService.countNew(taskCode, sku, num, errorFlag);
				
				String msg = (String)resultMap.get("msg");
				json.put("goodNum", resultMap.get("goodNum"));
				json.put("status", msg);
				json.put("newFlag", resultMap.get("newFlag"));
				if("success".equals(msg)){
					List<InstorageCountItem> items=this.instorageCountTaskService.findByTaskCode(taskCode);
					for(InstorageCountItem item:items){
						item.setEdiGoodsSku(ediGoodsSkuService.findByCustomerCodeAndSku(item.getCustomerCode(),item.getSku()));
					}
                    List<InstorageBillItemPre> preItems = (List<InstorageBillItemPre>)resultMap.get("preitems");
					if(null != preItems ){
						Map<String,Integer> countMap = new HashMap<String,Integer>();						
						for(InstorageBillItemPre itemPre : preItems){
							countMap.put(itemPre.getSkuCode(), itemPre.getGoodsNum());
						}
						for(InstorageCountItem cItem : items){
							cItem.setPlanNum(countMap.get(cItem.getSku()));
						}
					}
					json.put("items", items);
				}else if("NoGoodSku".equals(msg)){
					json.put("content", msg);
				}else if("NoConfigure".equals(msg)){
					json.put("content", msg);
				}
				logger.info("点收新流程--点收结果:{}--{}--{}--{}",taskCode, sku, num,msg);
			}
			
			
		} catch (Exception e) {
			
			json.put("status","error");
			json.put("content",e.getMessage());
			logger.error("error",e);
		} finally {
            if (isLockSuccess) {
                workTaskService.releaseLock("PC.ajaxCountNew", taskCode);
            }
            out.print(json.toString());
        }
	}
	
	/**
     * 点收新流程
     * @param request
     * @param response
     */
    @RequestMapping(value = "findSku")
    public void findSku(ServletRequest request,HttpServletResponse response) {

        JSONObject json = null;
        PrintWriter out = null;
        try {
            json = new JSONObject();
            out = response.getWriter();
            
            //获取参数
            String billCode=request.getParameter("billCode");
            String sku=request.getParameter("sku");
            String customerCode=request.getParameter("customerCode");
            
            EdiGoodsSku ediGoodsSku = this.ediGoodsSkuService.findByCustomerCodeAndSku(customerCode, sku);
            //add LiBin bug617 防止界面输入的数据和数据库中存在大小写的区别
            if(ediGoodsSku == null || !ediGoodsSku.getSku().equals(sku)){
                json.put("status","skuNotExist");
                json.put("content","SKU不存在(查看大小写)!");
                logger.error("---------sku :"+sku+" not exist!-----");
            }else {
                json.put("status", "success");
                json.put("isBatchMgmt", ediGoodsSku.getIsBatchMgmt() == null ? "0" : ediGoodsSku.getIsBatchMgmt());
                json.put("isShelfLifeMgmt", ediGoodsSku.getIsShelfLifeMgmt() == null? "0" : ediGoodsSku.getIsShelfLifeMgmt());
                
                json.put("batchList",this.instorageCountTaskService.batchList(billCode, sku));
                
            }
        } catch (Exception e) {
            json.put("status","error");
            json.put("content",e.getMessage());
            logger.error("error",e);
        }
        out.print(json.toString());
    }
	
	/**
	 * 散货点收
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "ajaxCount_Single")
	public void ajaxCount_Single(ServletRequest request,HttpServletResponse response) {

		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			
			String taskCode=request.getParameter("taskCode");
			String sku=request.getParameter("sku");
			
			//散货点收
			String msg=this.instorageCountTaskService.count_single(taskCode,sku);
			json.put("status", msg);
			if("success".equals(msg)){
				List<InstorageCountItem> itemList_single=this.instorageCountTaskService.loadByTaskCode(taskCode,"single");
				json.put("itemList_single", itemList_single);
			}
			
		} catch (Exception e) {
			
			json.put("status","error");
			json.put("content",e.getMessage());
			logger.error("error",e);
		}
		out.print(json.toString());
	}
	
	/**
	 * 整箱点收
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "ajaxCount_box")
	public void ajaxCount_box(ServletRequest request,HttpServletResponse response) {

		JSONObject json = null;
		PrintWriter out = null;
		try {
			json = new JSONObject();
			out = response.getWriter();
			
			String taskCode=request.getParameter("taskCode");
			String sku=request.getParameter("sku");
			Integer num=Integer.valueOf(request.getParameter("num"));
			String boxCode=request.getParameter("boxCode");
			
			
			//整箱点收
			String msg=this.instorageCountTaskService.count_box(taskCode,sku,num,boxCode);
			json.put("status", msg);
			if("success".equals(msg)){
				List<InstorageCountItem> itemList_box=this.instorageCountTaskService.loadByTaskCode(taskCode,"box");
				json.put("itemList_box", itemList_box);
			}
			
		} catch (Exception e) {
			
			json.put("status","error");
			json.put("content",e.getMessage());
			logger.error("error",e);
		}
		out.print(json.toString());
	}
	
	
	/**
	 * 删除点收明细项
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ajaxDeleteCountItem")
	@ResponseBody
	public String ajaxDeleteCountItem(ServletRequest request,HttpServletResponse response) {
		try {	
			Long itemId=Long.valueOf(request.getParameter("itemId")+""); 
			String result = this.instorageCountTaskService.deleteCountItem(itemId);
			if ("success".equals(result)) {                
			    return "true";
            }else {
                return "删除失败。任务已完成或不是点收中状态";
            }
		} catch (Exception e) {
			logger.error("error",e);
			return "网络繁忙，请稍后重试...";
		}
	}
	
	/**
	 * 导向点收确认页面
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "toInstorageCountConfirmPage/{taskId}", method = RequestMethod.GET)
	public String toInstorageCountConfirmPage(@PathVariable("taskId") Long taskId, Model model) {
		try {
		      InstorageCountTask  task=this.instorageCountTaskService.loadById(taskId);
		      model.addAttribute("task", task);
		      
		      List<InstorageCountItem> itemList=this.instorageCountTaskService.findByBillCode(task.getBillCode());
		      Map<String, Integer> countMap = EdiOrderUtil.count(itemList);
		      model.addAttribute("itemList", countMap);
			
		} catch (Exception e) {
			logger.error("error",e);
		}
		return "instorage/instorageCountConfirm";
	}
	
	/**
	 * 完成点收
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "ajaxFinishCount")
	public void ajaxFinishCount(ServletRequest request,HttpServletResponse response) {
	    String taskCode=request.getParameter("taskCode");
	    
		JSONObject json = new JSONObject();
		PrintWriter out = null;
		
		// add 20161019 bug:516 产生重复上架任务
		boolean isLockSuccess = false;
		try {
			out = response.getWriter();
			
			isLockSuccess = workTaskService.lock("ajaxFinishCount", taskCode, "-");
            if (!isLockSuccess) {
                json.put("result", false);
                json.put("content", "当前任务已在处理中，请勿重复处理！");
                out.print(json);
                return;
            }
            
			this.instorageCountTaskService.finishCountNew(taskCode);
			json.put("result", true);
		} catch (PaiUException e) {
			logger.error("error",e);
			json.put("result", false);
			json.put("content", e.getMessage());
		} catch (Exception e) {
			logger.error("error",e);
		} finally {
		    if (isLockSuccess) {
                workTaskService.releaseLock("ajaxFinishCount", taskCode);
            }
		}
		out.print(json);
	}
	
}
